package com.ql.reflect.beanUtil;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.ql.reflect.ReflectPoint;

/**
 * 使用内省的方式来操作javabean
 * 内省是什么？: 通过反射的方式访问javabean的技术
 * 使用BeanUtils
 */

public class TestIntroSpector {
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		ReflectPoint rp = new ReflectPoint(3, 5);
		//使用内省方法
		String propertyName = "x";   // 属性名为x
		Object retValue = getPropery(rp, propertyName);
		System.out.println(retValue);
		
		Object value = 8;
		PropertyDescriptor dp = new PropertyDescriptor(propertyName, rp.getClass());
		Method methodSetX = dp.getWriteMethod();
		methodSetX.invoke(rp, value);
		
		System.out.println(rp.getX());
	}
	
	private static Object getPropery(Object obj, String propertyName)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
		/*
		 * PropertyDescriptor pd = new PropertyDescriptor(propertyName,
		 * rp.getClass()); Method methodGetX = pd.getReadMethod(); Object
		 * retValue = methodGetX.invoke(rp);
		 */

		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

		Object retValue = null;
		for (PropertyDescriptor pd : pds) {
			if (pd.getName().equals(propertyName)) {
				Method methodGetX = pd.getReadMethod();
				retValue = methodGetX.invoke(obj);
			}
		}
		return retValue;
}  
	
}

